#define  _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    int numEnclaves(vector<vector<int>>& grid) {
        vector<vector<int>> dist(grid.begin(), grid.end());
        int m = grid.size(), n = grid[0].size();
        queue<pair<int, int>> q;
        for (int i = 0; i < m; i++)
        {
            if (dist[i][0]) dist[i][0] = 0, q.push({ i, 0 });
            if (dist[i][n - 1])dist[i][n - 1] = 0, q.push({ i, n - 1 });
        }
        for (int i = 0; i < n; i++)
        {
            if (dist[0][i])dist[0][i] = 0, q.push({ 0, i });
            if (dist[m - 1][i])dist[m - 1][i] = 0, q.push({ m - 1, i });
        }
        while (q.size())
        {
            auto [r, c] = q.front(); q.pop();
            static int dx[4] = { 0,0,1,-1 };
            static int dy[4] = { 1,-1,0,0 };
            for (int i = 0; i < 4; i++)
            {
                int x = r + dx[i];
                int y = c + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && dist[x][y])
                    dist[x][y] = 0, q.push({ x, y });
            }
        }

        int ret = 0;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                ret += dist[i][j];
        return ret;
    }
};